// @ts-check
import { defineConfig } from "socg"

export default defineConfig(() => ({
  generate: {
    output(code) {
      /** @type {Array<string>} */
      const imports = [`import { type ResultSchema } from "@/apis/model";`]
      if (~code.indexOf("serialize")) {
        imports.push(`import { serialize } from "query-parse-serialize";`)
      }
      const actions = ["httpGet", "httpPost", "httpPut", "httpDelete"].filter(action => ~code.indexOf(action))
      return [
        ...imports,
        `import { ${actions.join(', ')}, type ICapableFetchOpts } from "@/utils/request";`,
        code
      ].join('\r\n')
    },
    template({ URL, METHOD, QUERY, BODY, RESPONSE, REQUESTCONTENTTYPE }) {
      let fetcher = ""
      if (METHOD === "get" || METHOD === "delete") {
        const action = METHOD === 'get' ? 'httpGet' : 'httpPost'
        if (QUERY) {
          fetcher = `${action}<R>(${URL}, ${QUERY}, opts)`
        } else if (BODY) {
          fetcher = `${action}<R>(${URL}, ${BODY}, opts)`
        } else {
          fetcher = `${action}<R>(${URL}, void 0, opts)`
        }
      } else {
        const action = METHOD === 'post' ? 'httpPost' : 'httpPut'
        const contentType = REQUESTCONTENTTYPE === "url_encoded" ? "application/x-www-form-urlencoded" : "application/json"
        const search = QUERY ? `+ serialize(${QUERY}, { withPrefix: true })` : ''
        if (BODY) {
          fetcher = `${action}<R>(${URL}${search}, ${BODY}, {
            ...opts,
            header: {
              "content-type": "${contentType}",
              ...opts?.header
            }
          })`
        } else {
          fetcher = `${action}<R>(${URL}${search}, void 0, opts)`
        }
      }
      return `{
        send: <R extends ResultSchema<any> = ${RESPONSE}>(opts?: ICapableFetchOpts<R>) => ${fetcher}
      }`
    },
    dir: "src/apis/endpoint",
    model: "model.ts",
    locale: "zh-CN",
    allowImportingTsExtensions: false,
    verbatimModuleSyntax: false,
    filterTag(tag) {
      return !~["Upload", "Values", "GJP.Entries.WeChatApi"].indexOf(tag)
    },
  },
  customEnumMember(enumValue) {
    if (enumValue.toString().indexOf('=') !== -1) {
      const [name, initializer] = enumValue.toString().split('=')
      const value = Number(initializer)
      return {
        name,
        initializer: Number.isNaN(value) ? initializer : value
      }
    }
  },
  silent: false
}))
